# -*- coding: utf-8 -*-
import base64
import urllib
import requests
import json
import os
from PIL import Image
import io
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# API密钥配置
# 百度商标识别API接口文档地址：https://cloud.baidu.com/doc/IMAGERECOGNITION/s/Ok3bcxc59
API_KEY = ""
SECRET_KEY = ""

@app.route('/')
def index():
    return send_from_directory('.', 'index.html')

@app.route('/<path:path>')
def static_files(path):
    return send_from_directory('.', path)

@app.route('/api/get_token', methods=['POST'])
def get_access_token():
    """
    获取百度AI的Access Token
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials", 
        "client_id": API_KEY, 
        "client_secret": SECRET_KEY
    }
    
    try:
        response = requests.post(url, params=params)
        return jsonify(response.json())
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/recognize_logo', methods=['POST'])
def recognize_logo():
    """
    识别图片中的Logo
    """
    try:
        # 获取前端传递的base64图片数据
        data = request.get_json()
        image_base64 = data.get('image')
        
        if not image_base64:
            return jsonify({"error": "缺少图片数据"}), 400
        
        # 获取access_token
        token_data = requests.post(
            "https://aip.baidubce.com/oauth/2.0/token",
            params={
                "grant_type": "client_credentials",
                "client_id": API_KEY,
                "client_secret": SECRET_KEY
            }
        ).json()
        
        access_token = token_data.get("access_token")
        if not access_token:
            return jsonify({"error": "获取access_token失败"}), 500
        
        # 调用Logo识别API
        url = f"https://aip.baidubce.com/rest/2.0/image-classify/v2/logo?access_token={access_token}"
        # 修复：使用与test.py相同的方式处理图片数据
        payload = f"image={urllib.parse.quote_plus(image_base64)}"
        
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        
        response = requests.post(url, headers=headers, data=payload.encode("utf-8"))
        print(response.text)
        result_data = response.json()
        
        # 处理图片裁切
        if "result" in result_data and result_data["result"]:
            # 解码原始图片
            image_data = base64.b64decode(image_base64)
            original_image = Image.open(io.BytesIO(image_data))
            
            # 处理每个识别结果
            for i, item in enumerate(result_data["result"]):
                try:
                    location = item["location"]
                    
                    # 裁切图片
                    cropped_image = original_image.crop((
                        location["left"],
                        location["top"],
                        location["left"] + location["width"],
                        location["top"] + location["height"]
                    ))
                    
                    # 将裁切图片转换为base64
                    buffered = io.BytesIO()
                    cropped_image.save(buffered, format="JPEG")
                    cropped_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
                    
                    # 添加到返回结果中
                    item["cropped_image_base64"] = cropped_base64
                except Exception as e:
                    print(f"处理第{i}个识别结果时出错: {e}")
                    item["cropped_image_base64"] = None
        
        return jsonify(result_data)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/search_trademark', methods=['GET'])
def search_trademark():
    """
    搜索商标信息（使用本地实现的API）
    """
    try:
        # 获取查询参数
        keyword = request.args.get('keyword')
        pagenum = request.args.get('pagenum', '1')
        pagesize = request.args.get('pagesize', '40')

        if not keyword:
            return jsonify({
                "code": 400,
                "message": "缺少查询关键字",
                "data": None
            }), 400

        # 校验分页参数
        try:
            pagenum = int(pagenum)
            pagesize = int(pagesize)
        except ValueError:
            return jsonify({
                "code": 400,
                "message": "pagenum 和 pagesize 必须为整数",
                "data": None
            }), 400

        # 调用我们自己的商标搜索API (假设运行在8000端口)
        url = 'http://localhost:8000/search'
        params = {
            'name': keyword,
            'top_k': pagesize
        }

        # 发送请求到本地商标搜索API
        response = requests.post(url, data=params)

        # 检查响应状态
        if response.status_code == 200:
            search_result = response.json()
            
            # 转换为我们前端期望的格式
            transformed_result = {
                "result": {
                    "list": []
                }
            }
            
            # 处理每个商标结果
            for item in search_result.get("results", []):
                brand_info = item.get("brand_info", {})
                trademark_item = {
                    "name": brand_info.get("name", ""),
                    "regno": brand_info.get("regno", ""),
                    "classid": brand_info.get("classid", ""),
                    "appdate": brand_info.get("appdate", ""),
                    "firsttrialno": brand_info.get("firsttrialno", ""),
                    "firsttrialdate": brand_info.get("firsttrialdate", ""),
                    "announceno": brand_info.get("announceno", ""),
                    "announcedate": brand_info.get("announcedate", ""),
                    "pic": brand_info.get("pic", ""),
                    "agent": brand_info.get("agent", ""),
                    "status": brand_info.get("status", ""),
                    "registrant": brand_info.get("registrant", ""),
                    "score": item.get("score", 0)
                }
                transformed_result["result"]["list"].append(trademark_item)
            
            transformed_result["result"]["pagesize"] = len(transformed_result["result"]["list"])
            
            return jsonify({
                "code": 200,
                "message": "success",
                "data": transformed_result
            })
        else:
            return jsonify({
                "code": response.status_code,
                "message": f"API调用失败，状态码: {response.status_code}",
                "data": None
            }), response.status_code

    except Exception as e:
        import logging
        logging.basicConfig(level=logging.INFO)
        logging.error(f"搜索商标出错: {str(e)}", exc_info=True)
        return jsonify({
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e)
        }), 500

# 添加新的API端点，支持图片和名称同时搜索
@app.route('/api/search_trademark_with_image', methods=['POST'])
def search_trademark_with_image():
    """
    使用图片和名称搜索商标信息
    """
    try:
        # 获取请求数据
        if request.is_json:
            # 如果是JSON请求，包含base64编码的图片
            data = request.get_json()
            image_base64 = data.get('image')
            name = data.get('name', '')
            top_k = data.get('top_k', 10)
            
            if not image_base64 and not name:
                return jsonify({
                    "code": 400,
                    "message": "需要提供图片或名称",
                    "data": None
                }), 400
                
            # 准备请求到本地API的数据
            url = 'http://localhost:8000/search'
            files = None
            data = {'top_k': top_k}
            
            if image_base64:
                # 解码base64图片
                image_data = base64.b64decode(image_base64)
                files = {'image': ('search_image.jpg', image_data, 'image/jpeg')}
                
            if name:
                data['name'] = name
                
            # 发送请求到本地商标搜索API
            response = requests.post(url, files=files, data=data)
        else:
            # 如果是表单请求，包含上传的文件
            name = request.form.get('name', '')
            top_k = request.form.get('top_k', 10)
            image_file = request.files.get('image')
            
            if not image_file and not name:
                return jsonify({
                    "code": 400,
                    "message": "需要提供图片或名称",
                    "data": None
                }), 400
                
            # 准备请求到本地API的数据
            url = 'http://localhost:8000/search'
            files = None
            data = {'top_k': top_k}
            
            if image_file:
                files = {'image': (image_file.filename, image_file.stream, image_file.content_type)}
                
            if name:
                data['name'] = name
                
            # 发送请求到本地商标搜索API
            response = requests.post(url, files=files, data=data)

        # 检查响应状态
        if response.status_code == 200:
            search_result = response.json()
            
            # 转换为我们前端期望的格式
            transformed_result = {
                "result": {
                    "list": []
                }
            }
            
            # 处理每个商标结果
            for item in search_result.get("results", []):
                brand_info = item.get("brand_info", {})
                trademark_item = {
                    "name": brand_info.get("name", ""),
                    "regno": brand_info.get("regno", ""),
                    "classid": brand_info.get("classid", ""),
                    "appdate": brand_info.get("appdate", ""),
                    "firsttrialno": brand_info.get("firsttrialno", ""),
                    "firsttrialdate": brand_info.get("firsttrialdate", ""),
                    "announceno": brand_info.get("announceno", ""),
                    "announcedate": brand_info.get("announcedate", ""),
                    "pic": brand_info.get("pic", ""),
                    "agent": brand_info.get("agent", ""),
                    "status": brand_info.get("status", ""),
                    "registrant": brand_info.get("registrant", ""),
                    "score": item.get("score", 0)
                }
                transformed_result["result"]["list"].append(trademark_item)
            
            transformed_result["result"]["pagesize"] = len(transformed_result["result"]["list"])
            
            return jsonify({
                "code": 200,
                "message": "success",
                "data": transformed_result
            })
        else:
            return jsonify({
                "code": response.status_code,
                "message": f"API调用失败，状态码: {response.status_code}",
                "data": None
            }), response.status_code

    except Exception as e:
        import logging
        logging.basicConfig(level=logging.INFO)
        logging.error(f"搜索商标出错: {str(e)}", exc_info=True)
        return jsonify({
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e)
        }), 500

if __name__ == '__main__':
    app.run(debug=True, port=5000)